<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>发布订阅</title>
</head>
<body>
	<script>
		class EventEmitter {
			constructor () {
				this.subs = {}
			}

			$on (event, handler) {
				this.subs[event] = this.subs[event] || []
				this.subs[event].push(handler)
			}

			$emit (event) {
				if (this.subs[event]) {
					this.subs[event].forEach(handler => {
						handler()
					})
				}
			}
		}

		class Dep {
			constructor () {
				this.subs = []
			}

			addSub (sub) {
				if (sub && sub.update) {
					this.subs.push(sub)
				}
			}

			notify () {
				this.subs.forEach(item => {
					item.update()
				})
			}
		}

		class Watcher {
			update () {
				console.log('update')
			}
		}

		const dep = new Dep()
		const watcher = new Watcher()

		dep.addSub(watcher)

		dep.notify()
	</script>
</body>
</html>